import Taro, { getSystemInfoSync } from '@tarojs/taro';
import i18n from 'i18n-js';
import moment from 'moment';
import Toast from './Toast';

const systemInfo = getSystemInfoSync();
const Platform = systemInfo.platform;

const accountInfo = wx.getAccountInfoSync();
/**
develop	开发版
trial	体验版
release	正式版
*/
const miniProgramVersion = accountInfo.miniProgram.envVersion; // 小程序是什么版本
const miniProgramVersionNum = accountInfo.miniProgram.version; // 小程序线上版本号，只有线上版本才能拿到，开发版和体验版不行

interface ISameDevice {
  mac: string;
  productKey: string;
}

function isDev() {
  return (
    process.env.NODE_ENV === 'development' || systemInfo.platform === 'devtools' || miniProgramVersion === 'develop'
  );
}

function isSameDevice(deviceA: ISameDevice, deviceB: ISameDevice) {
  return (
    (deviceA.mac && deviceA.mac.toUpperCase()) === (deviceB.mac && deviceB.mac.toUpperCase()) &&
    deviceA.productKey === deviceB.productKey
  );
}

function getDeviceId(device: IDevice) {
  if (device.deviceId && device.deviceId.length > 0) {
    return device.deviceId;
  }
  device.deviceId = `${device.mac.toLocaleUpperCase()}${device.productKey}`;
  return device.deviceId;
}

export function alarmTypeNum(alarmType: TAlarmType): number {
  switch (alarmType) {
    case 'alerts':
      return 5;
    case 'faults':
      return 4;
    case 'warn':
      return 3;
    case 'notice':
      return 2;
    default:
      return 0;
  }
}

// 告警排序规则，包括排序告警配置，排序发生的告警
export function alramInfoSort(a: any, b: any) {
  const { type: type1, level: level1, time: time1 } = a;
  const { type: type2, level: level2, time: time2 } = b;
  if (type1 !== type2) {
    const typeNum1 = alarmTypeNum(type1);
    const typeNum2 = alarmTypeNum(type2);
    return typeNum1 > typeNum2 ? -1 : 1;
  }
  // 同类型，比较等级
  if (level1 !== level2) {
    return level1 > level2 ? -1 : 1;
  }
  // 同等级，如果有时间的话，比较时间
  if (time1 && time2) {
    if (time1 === time2) {
      return 0;
    }
    return time1 < time2 ? -1 : 1;
  }
  return 0;
}

// 筛选设备告警配置，并按等级排序
export function filterAlarmConfig(config: any) {
  const { alarms } = config;
  if (alarms) {
    let arr = alarms.filter((i: any) => i.action && i.action.type && i.action.type !== 'none');
    if (arr) {
      arr = arr.sort(alramInfoSort);
    }
    // eslint-disable-next-line no-param-reassign
    config.alarms = arr;
  }
  return config;
}

// 是否为相同的告警
export function isSameAlarm(alarm1: any, alarm2: any) {
  if (!alarm1 || !alarm2) {
    return false;
  }
  const { time: time1, name: name1 } = alarm1;
  const { time: time2, name: name2 } = alarm2;
  return time1 === time2 && name1 === name2;
}

export function trim(text: string) {
  if (text === ' ') {
    // eslint-disable-next-line no-param-reassign
    text = ''; // 兼容AEP升级设备的时候会有一个空格，要把空格取消
  }
  try {
    // 把前后空格去掉
    text.replace(/(^\s*)|(\s*$)/g, '');
  } catch (error) {
    // eslint-disable-next-line no-param-reassign
    text = '';
  }
  return text;
}

export function checkName(name: string) {
  const result: { success: boolean; msg: string } = { success: true, msg: '' };
  if (name === '') {
    result.success = false;
    result.msg = i18n.t('THE_NAME_CANNOT_BE_EMPTY');
  }
  // 检查是否含有特殊字符
  if (/[&<>"']/im.test(name)) {
    result.success = false;
    result.msg = i18n.t('CANNOT_USE_SPECIAL_CHARACTERS');
  }
  return result;
}

const Localization = {
  country: () => {
    return 'CN';
  },
};

export function backToHazyRouter(url: string) {
  const routers = Taro.getCurrentPages();
  const index = routers.findIndex(i => i.route.includes(url));
  if (index > -1) {
    // 确实在模板页面里面了
    const delta = routers.length - index - 1;
    Taro.navigateBack({ delta });
  }
}

export function backToRouter(url: string) {
  const routers = Taro.getCurrentPages();
  const index = routers.findIndex(i => url === i.route);
  console.log('backToRouter', routers, index);
  if (index > -1) {
    // 确实在模板页面里面了
    const delta = routers.length - index - 1;
    Taro.navigateBack({ delta });
  }
}

export function getWxDeviceSN(mac: string) {
  return mac.toLocaleUpperCase().replace(/:/g, '_');
}

export function formattingNum(num: number) {
  return (Array(2).join('0') + num).slice(-2);
}

function formattingNumByLength(num: number, length: number) {
  return (Array(length).join('0') + num).slice(-length);
}

export function checkDeviceCanControl({ device, showToast = true }: { device?: IDevice; showToast?: boolean }) {
  const canControl = device && device.netStatus === 2;
  if (showToast && !canControl) {
    Toast.info(i18n.t('DEVICE_CAN_NOT_CONTROL'));
  }
  return canControl;
}

export function deviceIsWAN(device: IDevice) {
  return device && device.connectType == 'WAN';
}

export function deviceIsBleConnect(device: IDevice) {
  return device && device.connectType == 'BLE';
}

export function deviceIsBleBroadCast(device: IDevice) {
  return device && device.connectType == 'BLE_BROADCAST';
}

export const delay = (secounds: number) => new Promise(resolve => setTimeout(resolve, secounds * 1000));

export function getExpiryTime(expiryDays = 1, format = 'YYYY-MM-DD HH:mm:ss') {
  return moment().add(expiryDays, 'days').format(format);
}

export const hex2Arr = data => {
  const dataArr: number[] = [];
  for (let i = 0; i < data.length / 2; i++) {
    const index = i * 2;
    const str = data.substring(index, index + 2);
    dataArr.push(parseInt(str, 16));
  }
  return dataArr;
};

export function sleep(ms: number) {
  return new Promise((resolve) => setTimeout(resolve, ms))
}

const goLicense = (type: "private" | "agreement") => () => {
  Taro.navigateTo({
    url: `/pages/license/index?type=${type}`,
  });
};
const checkDeviceCanShare = (d: IDevice) => {
  if (d.deviceSourceType === 1 || d.deviceSourceType === 3) return true
  return false
}

export {
  isSameDevice,
  checkDeviceCanShare,
  Platform,
  Localization,
  getDeviceId,
  formattingNumByLength,
  isDev,
  miniProgramVersion,
  miniProgramVersionNum,
  goLicense
}
